package org.example.wumeng.controller;

import org.example.wumeng.service.T_userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.wumeng.pojo.User;
import org.example.wumeng.pojo.Result;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class T_userController {

    @Autowired
    private T_userService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");

            if (username == null || password == null) {
                return Result.badRequest("用户名和密码不能为空");
            }

            User user = userService.login(username, password);

            // 生成token（简化版，实际应该使用JWT）
            String token = "token_" + user.getId() + "_" + System.currentTimeMillis();

            // 根据用户类型返回不同的跳转信息
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);

            if ("ADMIN".equals(user.getUserType())) {
                result.put("redirectUrl", "/admin/books");
                result.put("message", "管理员登录成功");
            } else {
                result.put("redirectUrl", "/browse/books");
                result.put("message", "用户登录成功");
            }

            return new Result<>(200, "登录成功", result, null);

        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户注册（只能注册普通用户）
     */
    @PostMapping("/register")
    public Result<Long> register(@RequestBody User user) {
        try {
            Long userId = userService.register(user);
            return new Result<>(200, "注册成功", userId, null);
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        try {
            boolean exists = userService.existsByUsername(username);
            return new Result<>(200, "检查完成", exists, null);
        } catch (Exception e) {
            return Result.error("检查用户名失败: " + e.getMessage());
        }
    }
}